<template>
  <el-container>
    <el-header height="36px">
      <header-title v-if="titleShow" :title="headerTitle" />
    </el-header>
    <div style="padding: 15px 25px 0px; width: 100%;">
      <TCollapse title="项目基础信息">
        <iframe id="iframe1" ref="basinRef" style="width:100%;" scrolling="no" frameborder="0" :src="basinRefSrc" />
      </TCollapse>
      <!-- <TCollapse title="项目站址信息">
        <iframe id="iframe2" ref="siteInfoRef" style="width:100%;" scrolling="no" frameborder="0" :src="siteInfoSrc" />
      </TCollapse> -->
      <TCollapse title="项目专属信息">
        <projectProprietary ref="projectProprietary" :select-list="selectList" :form-val="Proprietarylist" />
      </TCollapse>
      <TCollapse title="决算送审表">
        <actualBudgetAllForm ref="actualBudgetAllForm" :form="Proprietarylist" @proSent="proSent" @editDatas="editDatas" />
      </TCollapse>
      <TCollapse title="附件">
        <iframe ref="myIframeFjRef" style="width:100%;" frameborder="0" scrolling="no" :src="fuJianSrc" />
      </TCollapse>
      <FooterButton :button-disable="buttonDisable" @handleClose="handleClose" />
    </div>
  </el-container>
</template>

  <script>
  import FooterButton from '@/components/footer/details'
  import HeaderTitle from '@/components/basic/HeaderTitle'
  import actualBudgetAllForm from '@/views/actualBudget/business/actualBudgetAllForm'
  import projectProprietary from '@/views/actualBudget/business/projectProprietary'

  import TCollapse from '@/components/basic/TCollapse.vue'
  import {getDropdownData} from '@/api/common'
  import {
    getWFWorkItem,
    queryFinalSentNew,
    getPrjDetail,
    updateFinancialDataNew,
    finalSentAuditNew,
    trailFeeVerifyNew,
  } from '@/api/actualBudget'

  export default {
      name: 'AcceptMangeDetail',
      components: {
          FooterButton,
          HeaderTitle,
          projectProprietary,
          actualBudgetAllForm,
          TCollapse
      },
      data() {
          return {
              headerTitle: '',
              junNanUrl: process.env.VUE_APP_JUNNAN_IFRAME_URL,
              fileUrl: process.env.VUE_APP_ZHONGRUAN_URL,
              activeNames: ['demo1', 'demo2', 'demo3'],
              buttonDisable: ['close'],
              newCollapseList: {},
              selectList: {},
              Proprietarylist: {},
              lcList: {}, // 获取流程参数
              basicList: {}, // 基本信息
              titleShow: true, // 默认展示头部信息,综合查询时候不展示
              urlList: {},
              basicInfo: {},
              detailData: {},
              proprietaryInfo: {},
              siteInfo: {},
              secondaryType: '',
              basinRefSrc: '',
              // siteInfoSrc: '',
              fuJianSrc: '',
              id: '', // id
              prjId: '',
              btnConfig: 'A' // 默认传A .综合查询传B
          }
      },
      async mounted() {
        this.getList() // 获取基本信息
        this.getSelectData() // 字典
      },
      async created() {
        var urlVal = window.location.href
        this.urlList = this.GetRequest(urlVal)
        if (this.urlList.workItemId) {
          const { data } = await getWFWorkItem({ workItemId: this.urlList.workItemId })
          this.lcList = data // 获取流程参数信息
          this.prjId = data.bizObject.prjId
        } else {
          this.prjId = this.urlList.prjId
        }
        this.ifarmSrcPram()
        this.SetData() // 获取专属信息
      },
      methods: {
           // 获取基本信息 专属信息 站址信息
          getList() {
            window.addEventListener('message', (event) => {
              const base_url = ''
              if (event.origin === base_url) {
                return
              }
              // 基本信息高度
              if (event.data.type === 'basicHeight') {
                this.$refs.basinRef.style.height = event.data.data + 'px'
              }
              // // 站址信息高度
              // if (event.data.type === 'siteHeight') {
              //   this.$refs.siteInfoRef.style.height = event.data.data + 'px'
              // }
              if (event.data.type === 'basicInfo') {
                this.basicInfo = JSON.parse(event.data.data)
                // console.log('基本信息')
              }
              if (event.data.type === 'proprietaryInfo') {
                // console.log('专属信息')
              }
              if (event.data.type === 'siteInfo') {
                this.siteInfo = JSON.parse(event.data.data)
                // console.log('站址信息')
              }
              if (event.data.type === 'attachment') {
                this.$refs.myIframeFjRef.style.height = event.data.height + 'px'
                // console.log('附件高度')
              }
              })
          },
          // 获取url 携带参数
          GetRequest(url) {
            var theRequest = {}
            if (url.indexOf('?') !== -1) {
                var str = url.substr(1)
                var strs = str.split('?')
                var strsList = strs[1].split('&')
                for (var i = 0; i < strsList.length; i++) {
                  theRequest[strsList[i].split('=')[0]] = strsList[i].split('=')[1]
                }
            }
            return theRequest
          },
          // 获取下拉框数据字典
          async getSelectData() {
              const arr = ['IS_PUSH']
              for (const i in arr) {
                  const res = await getDropdownData(arr[i])
                  this.$set(this.selectList, arr[i], res.data)
              }
          },
        async repairSetDataOne() { 
          if (this.urlList.type === 'done' || this.urlList.type === '1') {
                this.buttonDisable = []
                this.btnConfig = 'B'
                this.titleShow = false
            }
        },
        async repairSetDataTwo() { 
          const queryFinalSent = await queryFinalSentNew({ prjId: this.prjId })
            if (+queryFinalSent.code !== '200') {
              return Promise.reject()
            }
            return queryFinalSent.data
        } ,
        async repairSetDataThree(nullList){
          let result = nullList?.finalTime
          if (nullList.isPush === '03') {
            result = nullList.finalTime === '2' ? '异常项目退回' : '资料严重不合格'
          }
          return result
        },
        async repairSetDataFour(nullList){
          if (nullList.isPush === '02') {
            this.$refs.actualBudgetAllForm.proSentShow = false
            this.$refs.actualBudgetAllForm.editDatasShow = false
          }
        },
        async repairSetDataFive(nullList_ing, types) {
          let result = nullList_ing
          if (types === '' || types === null) {
            result = this.formatCurrency(0)
          } else {
            result = this.formatCurrency(types)
          }
          return result
        },
          // 初始化
          async SetData() {
            // 初始化判断 是否可操作 暂不需要
            await this.repairSetDataOne()
            var nullList = {}
            // 获取项目专属信息
            nullList = await this.repairSetDataTwo()
            nullList.finalTime=await this.repairSetDataThree(nullList)
            // if (nullList.isPush === '03') {
            //   if (nullList.finalTime === '2') {
            //     nullList.finalTime = '异常项目退回'
            //   } else {
            //     nullList.finalTime = '资料严重不合格'
            //   }
            // }
            //  if (nullList.isPush === '02') {
            //   this.$refs.actualBudgetAllForm.proSentShow = false
            //   this.$refs.actualBudgetAllForm.editDatasShow = false
            // }
            await this.repairSetDataFour(nullList)
            // 设置字典值
            // 获取主表id传到从表
            // this.id = infos.ID
            var des = nullList.desInvest
            var jaAmt = nullList.jaAmt
            var equAmt = nullList.equipmentAmt
            var prep = nullList.prepaidAmt
            var other = nullList.otherAmt
            var ssje = nullList.trailFee
            var zgzg = nullList.zgzgAmt

            // if (des === '' || des === null) {
            //   nullList.desInvest = this.formatCurrency(0)
            // } else {
            //   nullList.desInvest = this.formatCurrency(des)
            // }
            nullList.desInvest = await this.repairSetDataFive(nullList.desInvest, des)
            // if (jaAmt === '' || jaAmt === null) {
            //   nullList.jaAmt = this.formatCurrency(0)
            // } else {
            //   nullList.jaAmt = this.formatCurrency(jaAmt)
            // }
            nullList.jaAmt = await this.repairSetDataFive(nullList.jaAmt, jaAmt)
            // if (equAmt === '' || equAmt === null) {
            //   nullList.equipmentAmt = this.formatCurrency(0)
            // } else {
            //   nullList.equipmentAmt = this.formatCurrency(equAmt)
            // }
            nullList.equipmentAmt = await this.repairSetDataFive(nullList.equipmentAmt, equAmt)
            // if (prep === '' || prep === null) {
            //   nullList.prepaidAmt = this.formatCurrency(0)
            // } else {
            //   nullList.prepaidAmt = this.formatCurrency(prep)
            // }
            nullList.prepaidAmt =await this.repairSetDataFive(nullList.prepaidAmt, prep)
            // if (other === '' || other === null) {
            //   nullList.otherAmt = this.formatCurrency(0)
            // } else {
            //   nullList.otherAmt = this.formatCurrency(other)
            // }
            nullList.otherAmt =await this.repairSetDataFive(nullList.otherAmt, other)
            // if (ssje === '' || ssje === null) {
            //   nullList.trailFee = this.formatCurrency(0)
            // } else {
            //   nullList.trailFee = this.formatCurrency(ssje)
            // }
            nullList.trailFee=await this.repairSetDataFive(nullList.trailFee, ssje)
            // if (zgzg === '' || zgzg === null) {
            //   nullList.zgzgAmt = this.formatCurrency(0)
            // } else {
            //   nullList.zgzgAmt = this.formatCurrency(zgzg)
            // }
            nullList.zgzgAmt =await this.repairSetDataFive(nullList.zgzgAmt, zgzg)
            let dataStr = nullList.isPush
            if (Array.isArray(this.selectList['IS_PUSH']) && this.selectList['IS_PUSH'].length) {
              dataStr = this.selectList['IS_PUSH'].find(item => item.dictId === nullList.isPush).dictName
            }
            this.Proprietarylist = {
              isPushName: dataStr,
              ...nullList
            }
          },
          // ifarm src 传参
          async ifarmSrcPram() {
            await getPrjDetail({ prjId: this.prjId }).then(res => {
            for (const i in res.data) {
                this.$set(this.detailData, i, res.data[i])
            }
                this.headerTitle = res.data.prjName
                this.basicList = res.data // 获取基本信息
            })
            if (this.urlList.workItemId) {
              const { data } = await getWFWorkItem({ workItemId: this.urlList.workItemId })
              this.lcList = data // 获取流程参数信息
              this.prjId = data.bizObject.prjId
            }
            var iframeParams = {
              prjType: this.basicList.prjType,
              nodeId: this.lcList.activityDefID, // activityDefID 流程节点ID
              buildModes: this.basicList.buildModes,
              orgId: this.basicList.orgId,
              towerType: '2',
              roomType: '0',
              prjId: this.basicList.prjId,
              projectId:this.prjId,
              prjStage: 'G',
              fileSupplierCode: '', // 供应商接口
              isChange: '0', // 默认传0
              operateType: '1', // 默认传1
              btnConfig: this.btnConfig // 默认传A
            }
            // 基本信息
            this.basinRefSrc = `${this.junNanUrl}design/basicInfo?prjId=${this.prjId}`
            // 项目站址信息
            // this.siteInfoSrc = `${this.junNanUrl}design/siteInfo?prjId=${this.prjId}`
            // 附件信息
             this.fuJianSrc = `${this.fileUrl}attachmentInfo?prjType=${iframeParams.prjType}&nodeId=${iframeParams.nodeId}&buildModes=${iframeParams.buildModes}&towerType=${iframeParams.towerType}&roomType=${iframeParams.roomType}&prjId=${iframeParams.prjId}&prjStage=${iframeParams.prjStage}&fileSupplierCode=${iframeParams.fileSupplierCode}&isChange=${iframeParams.isChange}&operateSystem=${iframeParams.operateSystem}&operateType=${iframeParams.operateType}&btnConfig=${iframeParams.btnConfig}&orgId=${iframeParams.orgId}&projectId=${iframeParams.projectId}`
          },
          // 更新财务数据
          async editDatas() {
            // const prjName = this.basicInfo.projectName // 项目名称：
            // const prjCode = this.basicInfo.prjCode // 项目编号：
            // const isPush = this.Proprietarylist.isPush // 送审状态
            // const returnType = this.Proprietarylist.returnType // 退回类型
            // const projects = { prjName: prjName, prjCode: prjCode, isPush: isPush, returnType: returnType, id: id }
            const id = this.Proprietarylist.id // 基本信息的 ID
            const projects = { tfaId: id, operation: 1 } // 是否直接 直接为 1
            if (confirm('是否更新财务数据？')) {
              const updateFinancialData = await updateFinancialDataNew(projects)
              if (updateFinancialData.code === '200') {
                    this.$message({
                        message: updateFinancialData.message,
                        type: 'success'
                    })
              } else if (updateFinancialData.code === '500') {
                  this.$message({
                      message: '更新财务数据出现错误！',
                      type: 'error'
                  })
              } else {
                  this.$message({
                      message: updateFinancialData.message,
                      type: 'error'
                  })
              }
            }
          },
          // 项目送审按钮，insert操作历史页面
          async proSent() {
            var isPush = this.Proprietarylist.isPush // 送审状态
            if (isPush === '02') {
              this.$message({
                  message: '项目已送审',
                  type: 'warning'
              })
              return
            } else {
              this.optimizeNewThree()
            }
          },
          // 2024-10-09 阻断问题if过多解决方案
          async optimizeNewThree() {
            var num = '' // 10分钟为限
              var myDate = new Date()
              var nowTime = this.formatDate(myDate, 'yyyy-MM-dd HH:mm:ss') // 当前系统时间
              var updateTime = this.Proprietarylist.updateTime
               // 转Date类型
               var time = nowTime
                  time = time.replace(/-/g, ':').replace(' ', ':')
                  time = time.split(':')
              var time1 = new Date(time[0], (time[1] - 1), time[2], time[3], time[4], time[5])
              if (updateTime) {
                var endTime = this.formatDate(updateTime, 'yyyy-MM-dd HH:mm:ss') // 项目数据更新时间
                var date2 = endTime
                    date2 = date2.replace(/-/g, ':').replace(' ', ':')
                    date2 = date2.split(':')
                var time2 = new Date(date2[0], (date2[1] - 1), date2[2], date2[3], date2[4], date2[5])
                var timeCha = ((time1.getTime() - time2.getTime()) / 60 / 1000)
                    num = parseInt(timeCha)// 10分钟为限
              }

              if (endTime === '' || endTime === null || num > 10) {
                  this.optimizeNewOne()
              } else {
                this.optimizeNewTwo()
              }
          },
          // 2024-10-09 阻断问题if过多解决方案
          async optimizeNewOne() {
                const id = this.Proprietarylist.id // 基本信息的 ID
                const projects = { tfaId: id, operation: 0 } // 是否为 0
                const updateFinancialData = await updateFinancialDataNew(projects)
                if (updateFinancialData.code === '200') {
                    this.queryTrailAmt()
                } else if (updateFinancialData.code === '500') {
                    this.$message({
                        message: '更新财务数据出现错误！',
                        type: 'error'
                    })
                } else {
                    this.$message({
                        message: updateFinancialData.message,
                        type: 'error'
                    })
                }
          },
          // 2024-10-09 阻断问题if过多解决方案
          async optimizeNewTwo() {
            const trailAmt = this.Proprietarylist.trailFee.split(',').join('') // 送审金额
                if (trailAmt > 5000000.00) {
                  this.$confirm('该项目的送审金额超500万,是否确认送审？', '提醒', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                      cancelButtonClass: 'pms-zr-button',
                      confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
                  })
                  .then(async() => {
                      this.optimizeNewFour()
                  })
                } else {
                    this.optimizeNewFour()
                }
          },
          // 2024-10-09 阻断问题if过多解决方案
          async optimizeNewFour() {
            const finalSentAudit = await finalSentAuditNew({ tfaId: this.Proprietarylist.id, isInertHistory: 1 })
                      if (finalSentAudit.code === '200') {
                          this.$message({
                            message: finalSentAudit.message,
                            type: 'success'
                          })
                          this.handleClose('ok') // 关闭
                      } else if (finalSentAudit.code === '500') {
                          this.$message({
                              message: '送审数据出现错误！',
                              type: 'error'
                          })
                      } else {
                          this.$message({
                              message: finalSentAudit.message,
                              type: 'error'
                          })
                      }
          },
          // 查询送审项目的送审金额是否大于500W
          async queryTrailAmt() {
            const prjCode = this.basicInfo.prjCode // 项目编号：
            const trailFeeVerify = await trailFeeVerifyNew({ prjCode: prjCode })
            if (trailFeeVerify.code === '200') {
                this.sentPrjs()
            } else {
              this.$confirm('送审项目中存在送审金额超500万元项目,是否确认送审？', '删除提醒', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                  cancelButtonClass: 'pms-zr-button',
                  confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
              })
              .then(async() => {
                this.sentPrjs()
              })
            }
          },
          // 送审
          async sentPrjs() {
            const finalSentAudit = await finalSentAuditNew({ tfaId: this.Proprietarylist.id, isInertHistory: 1 })
            if (finalSentAudit.code === '200') {
                  this.$message({
                    message: finalSentAudit.message,
                    type: 'success'
                  })
                  this.handleClose('ok') // 关闭
              } else if (finalSentAudit.code === '500') {
                  this.$message({
                      message: '送审数据出现错误！',
                      type: 'error'
                  })
              } else {
                  this.$message({
                      message: finalSentAudit.message,
                      type: 'error'
                  })
              }
            if (finalSentAudit.code === '200') {
                this.$message({
                    message: finalSentAudit.returnMsg,
                    type: 'warning'
                })
            }
          },
          // 关闭
          handleClose(action) {
            if (action === 'close') {
              // console.log('关闭')
            } else if (window.CloseOwnerWindow) {
              return window.CloseOwnerWindow(action)
            } else {
              return window.close()
            }
          },
          // jS文本框千分位显示
          formatCurrency(s, n) {
              n = n > 0 && n <= 20 ? n : 2
              s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + ''
              var l = s.split('.')[0].split('').reverse()
              var r = s.split('.')[1]
              var t = ''
              for (var i = 0; i < l.length; i++) {
                  t += l[i] + ((i + 1) % 3 === 0 && (i + 1) !== l.length ? ',' : '')
              }
              return t.split('').reverse().join('') + '.' + r
          },
          // 时间转换
          formatDate(date) {
            const myYear = date.getFullYear()
            let myMonth = date.getMonth() + 1
            let myWeekday = date.getDate()
            let myHour = date.getHours()
            let myMinute = date.getMinutes()
            let mySecond = date.getSeconds()

            if (myMonth < 10) {
              myMonth = '0' + myMonth
            }
            if (myWeekday < 10) {
              myWeekday = '0' + myWeekday
            }
            if (myHour < 10) {
              myHour = '0' + myHour
            }
            if (myMinute < 10) {
              myMinute = '0' + myMinute
            }
            if (mySecond < 10) {
              mySecond = '0' + mySecond
            }
            return (`${myYear}-${myMonth}-${myWeekday} ${myHour}:${myMinute}:${mySecond}`)
          }
      }
  }
  </script>

  <style>
  .el-collapse {
      margin-bottom: 15px;
  }
  .el-collapse-item {
      box-shadow: 0px 0px 6px 0px rgba(191, 192, 192, 0.52);
      /* 调整各个item之间的距离为20px */
      /* border: 1px; */
  }

  .el-collapse-item__wrap {
      padding: 0 20px;
      /* 为el-collapse-item的内容添加20像素的padding */
  }

  .el-collapse-item__header {
      padding-left: 20px;
      font-size: 14px;
      color: #333333;
      letter-spacing: 0;
      font-weight: 600;
  }

  .item_icon {
      width: 6px;
      background: rgb(235, 75, 75);
      height: 15px;
      margin-right: 10px;
      border-radius: 10px;
  }

  ::v-deep .content-box {
      width: 100%;
      border-radius: 3px;
      font-size: 12px;
      font-weight: 400;
      line-height: 28px;
  }
  </style>

